import _ from 'underscore';
import BaseModel from "../../base/models/BaseModel.js";
import Radio from 'backbone.radio';


function getCustomFieldValidation(field_name) {
    const validator = (value) => {
        const config = Radio.channel('config')
        const field_def = config.request('get:section', "common:" + field_name);
        if (field_def && field_def.required) {
            if (!value) {
                return "Veuillez saisir une valeur (" + field_def.title + ")"
            }
        }
    }
    return validator;
}

const CommonModel = BaseModel.extend({
    props: [
        'id',
        'name',
        'altdate',
        'date',
        'description',
        'address',
        'mentions',
        'workplace',


        'start_date',
        'end_date',
        'first_visit',
        'validity_duration',
        'insurance_id'
    ],
    validation: {
        date: {
            required: true,
            msg: "Veuillez saisir une date"
        },
        description: {
            required: true,
            msg: "Veuillez saisir un objet",
        },
        address: {
            required: true,
            msg: "Veuillez saisir une adresse",
        },
        start_date: getCustomFieldValidation("start_date"),
        end_date: getCustomFieldValidation("end_date"),
        start_date: getCustomFieldValidation("start_date"),
        first_visit: getCustomFieldValidation("first_visit"),
        validity_duration: getCustomFieldValidation("validity_duration"),
        insurance_id: getCustomFieldValidation("insurance_id"),
        workplace: getCustomFieldValidation('workplace'),
    },
    initialize(options) {
        this.on('saved', this.onDateChanged);
    },
    onDateChanged(attributes) {
        if (_.isObject(attributes)) {
            const channel = Radio.channel('facade');
            if (attributes.hasOwnProperty('date')) {
                channel.trigger('changed:date');
            }
            if (attributes.hasOwnProperty('insurance_id')) {
                channel.trigger('changed:task');
            }
        }
    },
    getInsuranceRate() {
        const insurance_id = this.get('insurance_id');
        let result = null;
        if (insurance_id) {
            const channel = Radio.channel('config')
            const insurance_options = channel.request('get:options', 'insurance_options');
            const insurance_option = insurance_options.find(x => x.id === parseInt(insurance_id));
            if (insurance_option) {
                result = insurance_option.rate;
            }
        }
        return result;
    }
});
export default CommonModel;